<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-action:add>新建</a-button>
      <a-button type="primary" icon="reload" @click="handleReloadResource">重新加载资源</a-button>
    </div>

    <s-table
      ref="resourceTable"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :alert="false"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">修改</a>
            <a-divider type="vertical" />
            <a @click="() => handleDelete(record)">删除</a>
          </template>
        </span>
    </s-table>
    <my-resource-form
      ref="resourceModalForm"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOK"
    />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getRoleList, addItem, deleteItem, updateItem, reloadResource } from '@/api/resource'
import MyResourceForm from './modules/MyResourceForm'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '菜单ID',
    dataIndex: 'menuIdPk'
  },
  {
    title: 'URL',
    dataIndex: 'url'
  },
  {
    title: '权限',
    dataIndex: 'permission'
  },
  {
    title: '描述',
    dataIndex: 'description'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'MyResourceList',
  components: {
    STable,
    Ellipsis,
    MyResourceForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getRoleList(requestParameters)
          .then(res => {
            return res.result
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      modalInfo: {}
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd () {
      this.modalInfo.title = '新增'
      this.mdl = null
      this.visible = true
    },
    handleDelete (row) {
      const table = this.$refs.resourceTable
      const msg = this.$message
      this.$confirm({
        title: '提示',
        content: `确定是否要删除吗?`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          console.log('OK')
          // 在这里调用删除接口
          return new Promise((resolve, reject) => {
            deleteItem(row).then((res) => {
              if (res.status === 200) {
                msg.success('删除成功')
                table.refresh()
              } else {
                msg.error('删除失败，请稍后重试！')
              }
            }).catch(() => {
              console.log('Oops errors!')
            })
            resolve()
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    handleEdit (record) {
      this.modalInfo.title = '修改'
      this.visible = true
      this.mdl = { ...record }
    },
    handleOK () {
      const form = this.$refs.resourceModalForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
            return new Promise((resolve, reject) => {
              updateItem(values).then(response => {
                if (response.status === 200) {
                  this.visible = false
                  this.confirmLoading = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  this.$refs.resourceTable.refresh()

                  this.$message.success('修改成功')
                } else {
                  this.$message.error('修改失败，请稍后重试！')
                }
                resolve(response)
              }).catch(error => {
                reject(error)
              })
            })
          } else {
            return new Promise((resolve, reject) => {
              addItem(values).then(response => {
                if (response.status === 200) {
                  this.visible = false
                  this.confirmLoading = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  this.$refs.resourceTable.refresh()
                  this.$message.success('新增成功')
                } else {
                  this.$message.error('新增失败，请稍后重试！')
                }
                resolve()
              }).catch(error => {
                reject(error)
              })
              resolve()
            })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.roleModalForm.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleReloadResource () {
      const table = this.$refs.resourceTable
      const msg = this.$message
      // 在这里调用删除接口
      return new Promise((resolve, reject) => {
        reloadResource().then((res) => {
          if (res.status === 200) {
            msg.success('加载成功')
            table.refresh()
          } else {
            msg.error('加载失败，请稍后重试！')
          }
        }).catch(() => {
          console.log('Oops errors!')
        })
        resolve()
      })
    }
  }
}
</script>

<style scoped>

</style>
